<template>
  <el-card>
    <div class="search-input-group">
      <el-form :model="searchForm" :inline="true">
        <el-form-item style="padding:5px" label="大学名称">
          <el-input 
            v-model="searchForm.universityName" 
            placeholder="请输入大学名称" 
            clearable
          />
        </el-form-item>
        <el-form-item style="padding:5px" label="省份">
          <el-input 
            v-model="searchForm.province" 
            placeholder="请输入省份" 
            clearable
          />
        </el-form-item>
        <el-form-item style="padding:5px" label="城市">
          <el-input 
            v-model="searchForm.city" 
            placeholder="请输入城市" 
            clearable
          />
        </el-form-item>
        <el-form-item style="padding:5px" label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 150px;" clearable>
            <el-option label="启用" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button @click="handleResetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <div class="btn-group">
      <el-button 
        v-if="btnGroup.addb" 
        type="primary" 
        :icon="Plus"
        @click="showAddDialog"
      >
        添加
      </el-button>
      <el-button 
        v-if="btnGroup.editb" 
        type="success" 
        :icon="Edit"
        @click="showEditDialog"
        :disabled="multipleSelection.length !== 1"
      >
        修改
      </el-button>
      <el-button 
        v-if="btnGroup.deleteb" 
        type="danger" 
        :icon="Delete"
        @click="handleDelete"
        :disabled="multipleSelection.length <= 0"
      >
        删除
      </el-button>
    </div>
    
    <el-table 
      :data="dataList" 
      style="width: 100%" 
      row-key="universityId"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="40" />
      <el-table-column type="index" label="序号" width="80" show-overflow-tooltip/>
      <el-table-column prop="universityName" label="大学名称" width="150" show-overflow-tooltip/>
      <el-table-column prop="universityCode" label="大学代码" width="120" show-overflow-tooltip/>
      <el-table-column prop="province" label="省份" width="100" show-overflow-tooltip/>
      <el-table-column prop="city" label="城市" width="100" show-overflow-tooltip/>
      <el-table-column prop="address" label="地址" show-overflow-tooltip/>
      <el-table-column prop="logo" label="Logo" width="100" show-overflow-tooltip>
        <template #default="scope">
          <el-image 
            v-if="scope.row.logo" 
            :src="scope.row.logo.trim()" 
            :preview-src-list="[scope.row.logo.trim()]"
            style="width: 40px; height: 40px; object-fit: cover;"
          />
          <span v-else>无Logo</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="80" show-overflow-tooltip>
        <template #default="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
            {{ scope.row.status === '0' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip />
      <el-table-column prop="updateTime" label="更新时间" width="180" show-overflow-tooltip />
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next"
      background
      @current-change="handleCurrentChange"
      class="pagination"
    />
  </el-card>
  
  <!-- 添加/修改大学的对话框 -->
  <el-dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    width="600px"
    @close="handleDialogClose"
  >
    <el-form
      :model="operateDataForm"
      :rules="operateDataFormRules"
      ref="operateDataFormRef"
      label-width="100px"
    >
      <el-form-item label="大学名称" prop="universityName">
        <el-input 
          v-model="operateDataForm.universityName" 
          placeholder="请输入大学名称"
        />
      </el-form-item>
      
      <el-form-item label="大学代码" prop="universityCode">
        <el-input 
          v-model="operateDataForm.universityCode" 
          placeholder="请输入大学代码"
        />
      </el-form-item>

      <el-form-item label="省份" prop="province">
        <el-input 
          v-model="operateDataForm.province" 
          placeholder="请输入省份"
        />
      </el-form-item>
      
      <el-form-item label="城市" prop="city">
        <el-input 
          v-model="operateDataForm.city" 
          placeholder="请输入城市"
        />
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-input 
          v-model="operateDataForm.address" 
          placeholder="请输入详细地址"
          type="textarea"
        />
      </el-form-item>

      <el-form-item label="Logo URL" prop="logo">
        <el-input 
          v-model="operateDataForm.logo" 
          placeholder="请输入Logo图片URL"
        />
        <el-image 
          v-if="operateDataForm.logo"
          :src="operateDataForm.logo.trim()" 
          style="width: 100px; height: 100px; margin-top: 10px; object-fit: cover;"
        />
      </el-form-item>
      
      <el-form-item label="状态" prop="status" v-if="isEdit">
        <el-select v-model="operateDataForm.status" placeholder="请选择状态">
          <el-option label="启用" value="0" />
          <el-option label="禁用" value="1" />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUniversityForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { getList, getSearchList, add, edit, remove } from "@/api/admin/university"
import { onMounted, reactive, ref, computed } from "vue"
import { useUserStore } from '@/stores/user'

// 搜索表单数据
const searchForm = reactive({
  universityName: '',
  province: '',
  city: '',
  status: ''
})

// 对话框相关数据
const dialogVisible = ref(false)
const isEdit = ref(false)
const operateDataFormRef = ref(null)

// 添加或修改数据表单
const operateDataForm = reactive({

  universityName: '',
  universityCode: '',
  province: '',
  city: '',
  address: '',
  logo: '',
  status: '0',
  dataVersion: 0
})

// 表单验证规则
const operateDataFormRules = {
  universityName: [
    { required: true, message: '请输入大学名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  universityCode: [
    { required: true, message: '请输入大学代码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请输入省份', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 对话框标题
const dialogTitle = computed(() => {
  return isEdit.value ? '修改大学信息' : '添加大学信息'
})

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(operateDataForm, {
    universityName: '',
    universityCode: '',
    province: '',
    city: '',
    address: '',
    logo: '',
    status: '0',
    dataVersion: 0
  })
}

// 显示编辑对话框
const showEditDialog = () => {
  isEdit.value = true
  dialogVisible.value = true
  // 填充表单数据
  const selectedItem = multipleSelection.value[0]
  Object.assign(operateDataForm, {
    ...selectedItem,
    dataVersion: selectedItem.dataVersion || 0
  })
}

// 对话框关闭时的处理
const handleDialogClose = () => {
  operateDataFormRef.value.resetFields()
}

// 固定参数源
const userStore = useUserStore()
const dataList = ref([])
const multipleSelection = ref([])
const isSerach = ref(false)
const btnGroup = reactive({
  addb: false,
  editb: false,
  deleteb: false
})
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取数据列表
const getDataList = () => {
  getList(pagination.currentPage).then(res => {
    dataList.value = res.data.records
    let opeStr = res.operateStr
    if (opeStr.includes("*") || opeStr.includes("a")) btnGroup.addb = true
    if (opeStr.includes("*") || opeStr.includes("d")) btnGroup.deleteb = true
    if (opeStr.includes("*") || opeStr.includes("u")) btnGroup.editb = true
    pagination.total = res.data.total
    pagination.pageSize = res.data.size
    pagination.currentPage = res.data.current
  })
}

// 处理搜索
const handleSearch = () => {
  isSerach.value = true
  getSearchList({...searchForm}, pagination.currentPage).then(res => {
    dataList.value = res.data.records
    pagination.total = res.data.total
    pagination.pageSize = res.data.size
    pagination.currentPage = res.data.current
  })
}

// 重置搜索
const handleResetSearch = () => {
  searchForm.universityName = ""
  searchForm.province = ""
  searchForm.city = ""
  searchForm.status = ""
  isSerach.value = false
  handleSearch()
}

// 添加或修改数据操作提交
const submitUniversityForm = () => {
  operateDataFormRef.value.validate(async (valid) => {
    if (valid) {
      const submitData = {
        ...operateDataForm,
        logo: operateDataForm.logo ? operateDataForm.logo.trim() : ''
      }
      
      if (isEdit.value) {
        await edit(submitData)
      } else {
        await add(submitData)
      }
      dialogVisible.value = false
      refreshList()
    }
  })
}

// 删除数据操作提交
const handleDelete = async () => {
  pagination.currentPage = 1
  const Ids = multipleSelection.value.map(item => item.universityId);
  await remove({list:Ids})
  refreshList()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 当前页改变时触发
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  refreshList()
}

// 刷新列表
const refreshList = () => {
  if (isSerach.value) handleSearch()
  else getDataList()
}

// 页面加载时获取数据
onMounted(() => {
  getDataList()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.btn-group {
  margin-bottom: 15px;
}

.btn-group .el-button {
  margin-right: 1px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.search-input-group {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-input-group .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}
</style>